package com.yingpai.fitness.dvp_2_0.main.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.ActivityManager;
import com.yingpai.fitness.dvp_2_0.common.util.ContextUtil;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.callback.WechatCallBack;
import com.yingpai.fitness.dvp_2_0.main.util.WechatLoginUtil;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.login.LoginBean;
import com.yingpai.fitness.entity.wx.WxLoginBean;
import com.yingpai.fitness.dvp_2_0.main.util.encrypt.RsaEncrypt;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * Created by ASUS on 2018/11/5.
 */

public class LoginActivity extends CommonActivity implements WechatCallBack, TextWatcher {
    @BindView(R.id.phoneEt)
    EditText phoneEt;
    @BindView(R.id.passwordEt)
    EditText passwordEt;
    @BindView(R.id.do_login)
    Button do_login;
    private String phoneNum;//手机号
    private String password;//密码
    private String beforeWord;
    private String specialWords = "-/:;()$&@\"_'`*#%[]{}!^￥+.,\\<>?~";//特殊字符专用串

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_login_layout);

    }

    @Override
    @OnClick({R.id.backIv, R.id.phoneEt, R.id.passwordEt, R.id.forgetPassTv, R.id.registerTv, R.id.do_login, R.id.wechat_login})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.backIv:
                finishActivity();
                break;
            case R.id.forgetPassTv:
                startActivity(ForgetPassWordActivity.class);
                break;
            case R.id.registerTv:
                startActivity(RegisterActivity.class);
                break;
            case R.id.do_login:
                if (checkInfoComplete()) {
                    login();
                }
                break;
            case R.id.wechat_login:
                WechatLoginUtil.getInstance().setWechatCallBack(this);
                WechatLoginUtil.getInstance().wechatLogin();
                break;
            case R.id.phoneEt:
                break;
            case R.id.passwordEt:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initData() {

    }

    private void login() {
        showDialog(this, "登录中...");
        String mPhoneNum = "";
        String mPassword = "";
        try {
            mPhoneNum = RsaEncrypt.getInstance(ContextUtil.getContext()).encryptWithBase64(phoneNum);
            mPassword = RsaEncrypt.getInstance(ContextUtil.getContext()).encryptWithBase64(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HttpParams httpParams = new HttpParams();
        httpParams.put("phoneNo", mPhoneNum);
        httpParams.put("password", mPassword);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.LOGIN, httpParams, Url.LOGIN, new Callback<LoginBean>() {
            @Override
            public void onSuccess(LoginBean loginBean) {
                dismissDialog();
                if (loginBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                    loginBean.getData().setRegisterId(JPushInterface.getRegistrationID(context));
                    SharedPreferencesHelp.putBean(Constant.TOKENBEAN, loginBean.getData());
                    //设置别名
                    JPushInterface.setAlias(context,loginBean.getData().getId(),"妖动动" + loginBean.getData().getId());
                    ActivityManager.getActivityManager().popAllActivity();
                    startFinishActivity(HomeActivity.class);
                } else {
                    showToast(loginBean.getMessage());
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                dismissDialog();
            }
        });
    }

    /**
     * 文本改变之前
     *
     * @param s
     * @param start
     * @param count
     * @param after
     */
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        beforeWord = s.toString();
    }

    /**
     * 文本改变中
     *
     * @param s
     * @param start
     * @param before
     * @param count
     */
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    /**
     * 文本改变之后
     *
     * @param s
     */
    @Override
    public void afterTextChanged(Editable s) {
        if (s.toString().equals(beforeWord)) {
            return;
        }
        if (!TextUtils.isEmpty(s.toString())) {
            for (int i = 0; i < s.toString().length(); i++) {
                if (specialWords.contains(s.toString().charAt(i) + "")) {
                    //发现了特殊字符，还原成之前的样子
                    passwordEt.setText(beforeWord);
                    passwordEt.setSelection(passwordEt.getText().toString().length());
                    return;
                }
            }
        }


        if (TextUtils.isEmpty(s)) {
            do_login.setEnabled(false);

        } else {
            do_login.setEnabled(true);
        }
    }

    /**
     * 非空判断
     *
     * @return
     */
    private boolean checkInfoComplete() {
        phoneNum = phoneEt.getText().toString().trim();
        if (!TextUtils.isEmpty(phoneNum)) {
            //手机号不为空，进行下一步
            if (phoneNum.length() == 11) {
                //手机号够11位
                password = passwordEt.getText().toString().trim();
                if (!TextUtils.isEmpty(password)) {
                    //密码不为空，没问题
                    if (password.length() >= 6) {
                        //密码长度没问题
                    } else {
                        //密码长度有问题
                        showToast("请输入6-12位密码");
                        passwordEt.requestFocus();
                        return false;
                    }
                } else {
                    //密码为空
                    showToast("请输入密码");
                    passwordEt.requestFocus();
                    return false;
                }
            } else {
                //手机号不够11位
                showToast("请输入正确的手机号码");
                phoneEt.requestFocus();
                return false;
            }
        } else {
            //手机号为空
            showToast("请输入手机号码");
            phoneEt.requestFocus();
            return false;
        }
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEvent(String messageEvent) {
        String[] str = messageEvent.split(",");
        if (str[0].equals("login")) {
            phoneEt.setText(str[1]);
            passwordEt.setText(str[2]);
        }
    }

    @Override
    public void callBack(BaseResp baseResp) {
        if (baseResp instanceof SendAuth.Resp) {
            SendAuth.Resp newResp = (SendAuth.Resp) baseResp;
            if (newResp.state.equals("wechat_sdk_login")) {
                HttpParams httpParams = new HttpParams();
                httpParams.put("code", newResp.code);
                showDialog(this, "登录中...");
                finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.WX_LOGIN, httpParams, Url.WX_LOGIN,
                        new Callback<WxLoginBean>() {
                            @Override
                            public void onSuccess(WxLoginBean wxLoginBean) {
                                dismissDialog();
                                if (wxLoginBean.getCode().equals(Constant.REQUEST_SUCCESS_0)) {
                                    if (wxLoginBean.getData().getData().getFlag().equals(Constant.REQUEST_SUCCESS_0)) {
                                        Bundle bundle = new Bundle();
                                        bundle.putString("infoUserWxId", wxLoginBean.getData().getData().getInfoUserWxId());
                                        startActivity(WeChatBindPhoneActivity.class, bundle);
                                    } else {
                                        wxLoginBean.getData().getData().setRegisterId(JPushInterface.getRegistrationID(context));
                                        SharedPreferencesHelp.putBean(Constant.TOKENBEAN, wxLoginBean.getData().getData());
                                        JPushInterface.setAlias(context,wxLoginBean.getData().getData().getId(),"妖动动" + wxLoginBean.getData().getData().getId());
                                        ActivityManager.getActivityManager().popAllActivity();
                                        startFinishActivity(HomeActivity.class);
                                    }
                                } else {
                                    showToast(wxLoginBean.getMessage());
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                dismissDialog();
                            }
                        });
            }
        }
    }
}
